'use strict'

const path = require('path')
const http = require('http')
const sockjs = require('sockjs')

class AppBootHook {
    constructor(app) {
        this.app = app
    }

    configWillLoad() {}

    async didLoad() {
        const dir = path.join(this.app.config.baseDir, 'app/mongo')
        const pro = this.app.mongoose.Model
        this.app.loader.loadToApp(dir, 'mongo', {
            inject: this.app,
            caseStyle: 'upper',
            filter(model) {
                return typeof model === 'function' && model.prototype instanceof pro
            },
        })
    }

    async willReady() {
        // 请将你的应用项目中 app.beforeStart 中的代码置于此处。
        if (
            Object.keys(this.app.model).length > 0 &&
            (this.app.config.env === 'local' || this.app.config.env === 'unittest')
        ) {
            // await this.app.model.sync()
        }
        // console.log(this.app.model)
    }

    async didReady() {
        // require('./config/seed')(this.app)
    }

    async serverDidReady() {
        const ctx = await this.app.createAnonymousContext()
        const sockjs_opts = { sockjs_url: 'http://127.0.0.1:9000/ws' }
        const sockjs_echo = sockjs.createServer(sockjs_opts)
        sockjs_echo.on('connection', async (conn) => {
            conn.on('data', async (msg) => {
                const params = ctx.service.chat.getUrlParams(conn.url)
                const res = await ctx.service.chat.insertMsg({ ...params, msg })
                if (res) conn.write(JSON.stringify(res))
            })
        })
        const server = http.createServer()
        sockjs_echo.installHandlers(server, { prefix: '/ws' })
        server.listen(9000, '127.0.0.1')
    }
}

module.exports = AppBootHook
